package zhenai

import (
	"gark-crawlers/config"
	"regexp"
	"strconv"

	"gark-crawlers/engine"
	"gark-crawlers/model"
)

var (
	ageRe      = regexp.MustCompile(`<div class="m-btn purple"[^>]+>([\d]+)岁</div>`)
	marriageRe = regexp.MustCompile(``)
	incomeRe   = regexp.MustCompile(`<div class="m-btn purple"[^>]+>月收入:([^<]+)</div>`)
	heightRe   = regexp.MustCompile(`<div class="m-btn purple"[^>]+>([\d]+)cm</div>`)
	urlIdRe    = regexp.MustCompile(`http://album.zhenai.com/u/([\d]+)`)
)

func parseProfile(contents []byte, url string, name string) engine.ParseResult {

	profile := model.Profile{}

	profile.Name = name
	age, err := strconv.Atoi(extractString(contents, ageRe))
	if err == nil {
		profile.Age = age
	}

	height, err := strconv.Atoi(extractString(contents, heightRe))
	if err == nil {
		profile.Height = height
	}

	profile.Marriage = extractString(contents, marriageRe)
	profile.Income = extractString(contents, incomeRe)

	return engine.ParseResult{
		Items: []engine.Item{
			{
				Url:     url,
				Type:    "zhenai",
				Id:      extractString([]byte(url), urlIdRe),
				Payload: profile,
			},
		},
	}
}

func extractString(contents []byte, re *regexp.Regexp) string {
	match := re.FindSubmatch(contents)
	if len(match) >= 2 {
		return string(match[1])
	} else {
		return ""
	}
}

type ProfileParser struct {
	userName string
}

func (p *ProfileParser) Parse(content []byte, url string) engine.ParseResult {
	return parseProfile(content, url, p.userName)
}

func (p *ProfileParser) Serialize() (name string, args interface{}) {
	return config.ParseProfile, p.userName
}

func NewProfileParser(name string) *ProfileParser {
	return &ProfileParser{userName: name}
}
